package com.aofeng.hybridwork.android;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.aofeng.hybrid.activity.HybridActivity;
import com.aofeng.hybrid.android.NativeBaseMethod;
import com.aofeng.hybrid.android.receiver.PhoneStatus;
import com.aofeng.hybrid.service.RestService;
import com.aofeng.hybrid.service.SqlService;
import com.aofeng.hybrid.util.CommUtil;
import com.aofeng.hybrid.util.LogUtil;
import com.aofeng.hybridwork.R;
import com.aofeng.hybridwork.android.bluetooth.sdk.BTPrint;
import com.aofeng.hybridwork.android.service.TickService;
import com.aofeng.hybridwork.android.task.DownloadAsyncTask;
import com.aofeng.hybridwork.android.task.FetchPaperTask;
import com.aofeng.hybridwork.android.task.RefreshPaperApprovalTask;
import com.aofeng.hybridwork.android.task.RefreshRepairApprovalTask;
import com.aofeng.hybridwork.android.task.SavePaperTask;
import com.aofeng.hybridwork.android.task.SavePaydata;
import com.aofeng.hybridwork.android.task.SavetTablebase;
import com.aofeng.hybridwork.android.task.UploadAsyncTask;
import com.aofeng.hybridwork.android.task.UploadRepairTask;
import com.aofeng.hybridwork.application.HybridApplication;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

/**
 * 城燃相关给的必须和本地交互的功能
 * Created by LGY on 2016-08-12.
 */
public class ChengRanNativeMethod extends NativeBaseMethod {
    /**
     * 获取该册号下的所有计划
     * @param webView
     * @param jo
     * @return
     */
    public static JSONObject getplan (WebView webView, String jo) throws JSONException, IOException {
        JSONArray array;
            JSONObject result = new JSONObject();
                result.put("code", 500);
                result.put("result", "不可处理异常。");
                SqlService ss = new SqlService(webView.getContext());
                JSONObject sql = new JSONObject();
                sql.put("sql",jo);
                array = ss.action(sql).getJSONArray("data");
//                int j = 0;
//                JSONObject jb;
//                for(int k = 0; k < array.length(); k++) {
//                    jb=array.getJSONObject(k-1);
//                    byte[]  content = InputStream2ByteArray(jb.getString("f_meter_path"));
//                    jb.put("context",content);
//                array.put(k,jo);
//                j++;
//            }
            result.put("code", 200);
            result.put("result", array);
            return result;
    }
    /**
     * 调用打印机
     * @param webView
     * @param context
     * @return
     */
    public static JSONObject print (WebView webView,String context) throws JSONException, IOException {
        JSONObject result = new JSONObject();
        result.put("code", 500);
        result.put("result", "不可处理异常。");

        BTPrint b = new BTPrint();
        b.open();
        Set<BluetoothDevice> binds = b.getBondedDevices();
        String address = "";
        for (BluetoothDevice device : binds) {
            address = device.getAddress();
        }

        b.connect(address);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e1) {
            result.put("code", 500);
            e1.printStackTrace();
        }
        try {
            result.put("code", 200);
            b.PrintData(context);
        } catch (Exception e) {
            result.put("code", 501);
            e.printStackTrace();
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e1) {
            result.put("code", 500);
            e1.printStackTrace();
        }
        b.close();
//        result.put("code", 200);
        return result;
    }

    /**
     * 获取图片内容
     * @param webView
     * @param path
     * @return
     */
    public static JSONObject context (WebView webView, String path) throws JSONException, IOException {
        JSONObject result = new JSONObject();
        result.put("code", 500);
        result.put("result", "不可处理异常。");
        byte[]  content = InputStream2ByteArray(path);
        String res = new String(content,"UTF-8");
        result.put("code", 200);
        result.put("result", res);
        return result;
    }

    private static  byte[] InputStream2ByteArray(String filePath) throws IOException {
        String path = filePath.substring(7,filePath.indexOf("?"));
        InputStream in = new FileInputStream(path);
        byte[] data = toByteArray(in);
        in.close();

        return data;
    }

    private static byte[] toByteArray(InputStream in) throws IOException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) out.write(buffer, 0, n);
        return out.toByteArray();
    }
    /**
     * 保存本次抄表底数
     * @param webView
     * @param jo
     * @throws Exception
     */
    public static void savetablebase(WebView webView,JSONObject jo) throws Exception {
        try{
            SavetTablebase dat = new SavetTablebase((HybridActivity)(webView.getContext()));
            dat.execute(new String[]{jo.getString("id"), jo.getString("pay")});
        } catch( Exception e) {
            LogUtil.d("NativeBaseMethod", "保存抄表数据出错");
            throw e;
        }
    }
    /**
     * 保存抄表并缴费的数据
     * @param webView
     * @param jo
     * @throws Exception
     */
    public static void savepaydata(WebView webView,JSONObject jo) throws Exception {
        try{
            SavePaydata dat = new SavePaydata((HybridActivity)(webView.getContext()));
            dat.execute(new String[]{jo.getString("id"), jo.getString("pay")});
        } catch( Exception e) {
            LogUtil.d("NativeBaseMethod", "保存抄表数据出错");
            throw e;
        }
    }

    /**
     * test
     * @param webView
     * @param id
     * @param tablebase
     */
    public static void test(WebView webView, String tablebase,String id) {
        try {
            SqlService ss = new SqlService(webView.getContext());
            ss.run("update t_handplan set f_tablebase = '" + tablebase  + "',f_meter_state = '已抄表' where f_userinfo_id =  '" + id +  "'");
            ChengRanNativeMethod.alert(webView, "操作成功!");
        } catch( Exception e) {
            ChengRanNativeMethod.alert(webView, "操作失败!");
        }
    }
    /**
     * 获取电话状态数据
     * @param webView
     * @return
     */
    public static JSONObject getPhoneStatus(WebView webView, String f_user_id) {
        Context context = webView.getContext();
        JSONObject result = new JSONObject();
        JSONObject jo = new JSONObject();
        try {
            result.put("code", 500);
            result.put("result", "不可处理异常。");
            jo.put("f_battery_level", PhoneStatus.getBatteryLevel(context));
            jo.put("f_internal_quote", PhoneStatus.getFreeInternalSDCapacity());
            jo.put("f_sn", PhoneStatus.getDeviceId(context));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String ymdToday = sdf.format(new Date());
            String traffic = CommUtil.getSharedPreference(context, "traffic_" + ymdToday + "_acc");
            if(traffic.length() == 0)
                jo.put("f_traffic", 0);
            else
                jo.put("f_traffic", Integer.valueOf(CommUtil.getSharedPreference(context, "traffic_" + ymdToday + "_acc"))/1000);
            jo.put("f_signal_strength", Integer.valueOf(CommUtil.getSharedPreference(context, "signalStrength")));
            jo.put("f_longitude", CommUtil.getSharedPreference(context, "longitude"));
            jo.put("f_latitude", CommUtil.getSharedPreference(context, "latitude"));
            jo.put("f_altitude", CommUtil.getSharedPreference(context, "altitude"));
            jo.put("f_provider", CommUtil.getSharedPreference(context, "provider"));
            jo.put("f_unread_notices", CommUtil.getSharedPreference(context, "f_unread_notices"));
            jo.put("f_preset_checks", CommUtil.getSharedPreference(context, "f_preset_checks"));
            jo.put("f_untreated_repairs", CommUtil.getSharedPreference(context, "f_untreated_repairs"));
            RestService rs = new RestService(context);
            sdf = new SimpleDateFormat("yyyy-MM-dd");
            ymdToday = sdf.format(new Date());
            JSONObject joRequest = new JSONObject();
            joRequest.put("action", "post");
            joRequest.put("url", HybridApplication.SQL_SERVICE_URL + URLEncoder.encode("获取签到状态", "UTF-8"));
            joRequest.put("data", "{\"data\":{\"f_user_id\":\"" + f_user_id + "\",\"f_date\":\"" + ymdToday + "\"}}");
            JSONArray array = (JSONArray) rs.execute(joRequest);
            if(array.length() == 1) {
                JSONObject responseObj = (JSONObject) array.getJSONObject(0);
                if (responseObj.has("f_signin_time") && !responseObj.isNull("f_signin_time")) {
                    jo.put("f_signin_time", responseObj.getString("f_signin_time"));
                }
                if (responseObj.has("f_knockoff_time") && !responseObj.isNull("f_knockoff_time")) {
                    jo.put("f_knockoff_time", responseObj.getString("f_knockoff_time"));
                }
            }
            result.put("code", 200);
            result.put("result", jo);
            return result;
        } catch(Exception e) {
            try {
                result.put("code", 500);
                result.put("result", "提取后台数据出错");
                return result;
            } catch (Exception ex) {
                return result;
            }
        }
    }

    /**
     * 计划预约
     * @param webView
     * @param id
     * @param dt
     */
    public static void prearrange(WebView webView, String id, String dt) {
        try {
            SqlService ss = new SqlService(webView.getContext());
            if(dt.length() == 0)
                ss.run("update t_check_plan_item set f_prearranged_date = null where id='" + id + "'");
            else
                ss.run("update t_check_plan_item set f_prearranged_date = '" + dt + "' where id='" + id + "'");
            ChengRanNativeMethod.alert(webView, "操作成功!");
        } catch( Exception e) {
            ChengRanNativeMethod.alert(webView, "操作失败!");
        }
    }

    /**
     * 静音
     * @param webView
     */
    public static void mute(WebView webView) {
        TickService ts = (TickService) HybridApplication.service;
        ts.mute();
    }

    /**
     * 设置偏好值
     * @param webView
     * @param key
     * @param value
     */
    public static void setPreference(WebView webView, String key, String value) {
        CommUtil.setSharedPreference(webView.getContext(), key, value);
    }


    /**
     *下载计划
     * @param webView
     * @param jo
     * @throws Exception
     */
    public static void downloadPlan(WebView webView,JSONObject jo) throws Exception {
        try{
            DownloadAsyncTask dat = new DownloadAsyncTask((HybridActivity)(webView.getContext()));
            dat.execute(new String[]{jo.getString("id"), jo.getString("index")});
        } catch( Exception e) {
            LogUtil.d("NativeBaseMethod", "下载计划出错。");
            throw e;
        }
    }
    /**
     * 更新安检单审核状态
     * @param webView
     * @param jo
     * @throws Exception
     */
    public static void refreshPaperApproval(WebView webView,JSONObject jo) throws Exception {
        try{
            RefreshPaperApprovalTask dat = new RefreshPaperApprovalTask((HybridActivity)(webView.getContext()));
            dat.execute(new String[]{jo.getString("f_plan_id")});
        } catch( Exception e) {
            LogUtil.d("NativeBaseMethod", "更新安检单审核状态出错。");
            throw e;
        }
    }

    /**
     * 更新维修审核状态
     * @param webView
     * @param jo
     * @throws Exception
     */
    public static void refreshRepairApproval(WebView webView,JSONObject jo) throws Exception {
        try{
            RefreshRepairApprovalTask dat = new RefreshRepairApprovalTask((HybridActivity)(webView.getContext()));
            dat.execute(new String[]{jo.getString("id")});
        } catch( Exception e) {
            LogUtil.d("NativeBaseMethod", "更新维修审核状态出错。");
            throw e;
        }
    }

    /**
     * 保存安检单
     * @param webView
     * @param jo
     * @throws Exception
     */
    public static void savePaper(WebView webView,JSONObject jo) throws Exception {
        try{
            SavePaperTask spt = new SavePaperTask((HybridActivity)(webView.getContext()), jo);

            spt.execute(new String[]{jo.has("callback") ? jo.getString("callback") : null});
        } catch( Exception e) {
            LogUtil.d("NativeBaseMethod", "保存工单出错。");
            throw e;
        }
    }

    /**
     * 提取安检单
     * @param webView
     * @param jo
     * @throws Exception
     */
    public static void fetchPaper(WebView webView,JSONObject jo) throws Exception {
        try{
            FetchPaperTask spt = new FetchPaperTask((HybridActivity)(webView.getContext()), jo);
            spt.execute(new String[]{jo.getString("callback")});
        } catch( Exception e) {
            LogUtil.d("NativeBaseMethod", "提取工单出错。");
            throw e;
        }
    }

    /**
     * 确认提示
     * @param webView
     * @param js
     * @throws Exception
     */
    public static void confirm(final WebView webView, String msg, final String js) throws Exception {
        AlertDialog.Builder builder = new AlertDialog.Builder(webView.getContext());
        builder.setTitle("系统确认");
        builder.setMessage(msg);
        builder.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                webView.loadUrl(js);
            }
        });
        builder.setNegativeButton(android.R.string.cancel, new AlertDialog.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setCancelable(false);
        builder.create();
        builder.show();

    }

    /**
     * 修改用户资料
     * @param webView
     * @param planItemId
     * @param criteria
     */
    public static  void updateUserPhone(final WebView webView, String planItemId, String criteria)  throws Exception {
        try {
            SqlService ss = new SqlService(webView.getContext());
            ss.run("update t_check_plan_item set " + criteria + " where id='" + planItemId + "'");
        } catch( Exception e) {
            LogUtil.d("NativeBaseMethod", "修改用户资料出错。");
            throw e;
        }
}

    /**
     * 上传安检单
     * @param webView
     * @param jo
     * @throws Exception
     */
    public static void uploadPaper(WebView webView, final JSONObject jo) throws Exception {
        try{
            final UploadAsyncTask uat = new UploadAsyncTask((HybridActivity)(webView.getContext()));
            final String[] params = new String[]{jo.getString("f_check_item_id"), jo.getString("f_checker_id"), jo.getString("data")};
            if(uat.findIfVerified(jo.getString("f_check_item_id"))) {
                AlertDialog.Builder builder = new AlertDialog.Builder(webView.getContext());
                builder.setTitle("系统提示");
                builder.setMessage("该工单已审核，您确定还要继续上传吗？");
                builder.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        uat.execute(params);
                    }
                });
                builder.setNegativeButton(android.R.string.cancel, new AlertDialog.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setCancelable(false);
                builder.create();
                builder.show();
            } else
            {
                uat.execute(params);
            }
        } catch( Exception e) {
            LogUtil.d("NativeBaseMethod", "上传工单出错。");
            throw e;
        }
    }

    /**
     * 上传维修单
     * @param webView
     * @param jo
     * @throws Exception
     */
    public static void uploadRepair(WebView webView,JSONObject jo) throws Exception {
        try{
            UploadRepairTask uat = new UploadRepairTask((HybridActivity)(webView.getContext()));
            uat.execute(new String[]{jo.getString("f_check_item_id"), jo.getString("f_checker_id"), jo.getString("data")});
        } catch( Exception e) {
            LogUtil.d("NativeBaseMethod", "上传工单出错。");
            throw e;
        }
    }

    /***
     * 修改表号
     * @param webView
     * @param meterNo
     * @param planItemId
     */
    public static void updateMeterNo(final WebView webView, final String meterNo, String planItemId){
        try {
            final Context context = webView.getContext();
            //查找计划内的用户对应的所有表
            RestService rs = new RestService(context);
            JSONObject joRequest = new JSONObject();
            joRequest.put("action", "post");
            joRequest.put("url", HybridApplication.SQL_SERVICE_URL + URLEncoder.encode("根据计划项找表", "UTF-8"));
            joRequest.put("data", "{\"data\":{\"id\":\"" + planItemId + "\"}}");
            JSONArray array = (JSONArray) rs.execute(joRequest);
            if(array.length() == 0)
                ChengRanNativeMethod.alert(webView, "查不到本户的表号数据！");
            else {
                //显示表号供选择
                Activity activity = (Activity)context;
                LayoutInflater inflater = activity.getLayoutInflater();
                final View layout = inflater.inflate(R.layout.chooser, (ViewGroup) activity.findViewById(R.id.meterLayout));
                final RadioGroup rg = (RadioGroup)layout.findViewById(R.id.meterGroup);
                int j = -1;
                int i = 0;
                for(i =0; i< array.length(); i++) {
                    JSONObject row = array.getJSONObject(i);
                    RadioButton rb = new RadioButton(activity);
                    rb.setText(row.getString("f_meter_no"));
                    rb.setTag(row.getString("id"));
                    rg.addView(rb);
                    if(rb.getText().equals(meterNo)) {
                        j = i;
                        rb.setChecked(true);
                    }
                }
                if(j == -1 && i != 0)
                    ((RadioButton)rg.getChildAt(0)).setChecked(true);
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setCancelable(false);
                builder.setView(layout);
                builder.setTitle("选择修改的表号");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        for(int i = 0; i < rg.getChildCount(); i++) {
                            if (((RadioButton)rg.getChildAt(i)).isChecked()) {
                                RestService rs = new RestService(context);
                                try {
                                    //更新表号
                                    JSONObject joRequest = new JSONObject();
                                    joRequest.put("action", "post");
                                    joRequest.put("url", HybridApplication.LOGIC_SERVICE_URL + URLEncoder.encode("现场修改表号", "UTF-8"));
                                    joRequest.put("data", "{\"data\":{\"id\":\"" + rg.getChildAt(i).getTag().toString() + "\", f_meter_no:\"" + meterNo + "\"}}");
                                    rs.execute(joRequest);
                                    ChengRanNativeMethod.alert(webView, "修改表号成功！");
                                }
                                catch(Exception e) {
                                    ChengRanNativeMethod.alert(webView, "修改表号失败！");
                                }
                                return;
                            }
                        }
                    }
                });
                builder.setNegativeButton("取消", null);
                builder.show();
            }
        } catch(Exception e) {
            ChengRanNativeMethod.alert(webView, "修改表号失败！");
        }
    }

    /**
     * 获取当前版本号
     * @param webView
     * @return
     */
    public static int getAppVersion(WebView webView) {
        return CommUtil.getVersionCode(webView.getContext());
    }

    /**
     * 备份数据库
     * @param webView
     */
    public static void backupDatabase(WebView webView) {
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            File dbFile = webView.getContext().getDatabasePath("hybrid.db");
            File exportDir = new File(Environment.getExternalStorageDirectory(), "dbBackup");
            if (!exportDir.exists()) {
                exportDir.mkdirs();
            }
            File backup = new File(exportDir, "hybrid.db");
            backup.createNewFile();
            inChannel = new FileInputStream(dbFile).getChannel();
            outChannel = new FileOutputStream(backup).getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } catch(Exception e) {
            e.printStackTrace();
        } finally{
            try
            {
                if(inChannel != null)
                    inChannel.close();
                if(outChannel != null)
                    outChannel.close();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}